// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

import type { LoginRequest, UserInfo } from "$lib/api/proto/user_api";
import { callApi } from "$lib/utils/call_utils";
import { appStore } from "./app.svelte";
import { parse, stringify } from "json-bigint";
import { noticeStore } from "./notice.svelte";


const USER_INFO_KEY = "userInfo";
const USER_SESSION_KEY = "userSession";

export class UserStore {
    private _userInfo: UserInfo | null = $state(null);
    private _userSession: string | null = $state(null);
    private _unReadMsgCount = $state(0);

    get userInfo() {
        return this._userInfo;
    }

    get userSession() {
        return this._userSession;
    }

    get unReadMsgCount() {
        return this._unReadMsgCount;
    }

    set userInfo(val: UserInfo | null) {
        this._userInfo = val;
        if (val == null) {
            sessionStorage.removeItem(USER_INFO_KEY);
        } else {
            sessionStorage.setItem(USER_INFO_KEY, stringify(val));
        }
    }

    set userSession(val: string | null) {
        this._userSession = val;
        if (val == null) {
            sessionStorage.removeItem(USER_SESSION_KEY);
        } else {
            sessionStorage.setItem(USER_SESSION_KEY, val);
        }
    }

    init() {
        const userInfoValue = sessionStorage.getItem(USER_INFO_KEY);
        if (userInfoValue != null) {
            this._userInfo = parse(userInfoValue) as UserInfo;
        }
        this._userSession = sessionStorage.getItem(USER_SESSION_KEY);
        noticeStore.init();
        this.syncUnReadMsgCount();
    }

    async login(request: LoginRequest) {
        const res = await callApi(appStore.userApiClient.login(request).response);
        this.userInfo = res.userInfo ?? null;
        this.userSession = res.sessionId;
        noticeStore.init();
    }

    async logout() {
        if (this._userSession == null) {
            return;
        }
        await callApi(appStore.userApiClient.logout({
            sessionId: this._userSession,
        }).response);
        this.userInfo = null;
        this.userSession = null;
        this._unReadMsgCount = 0;
    }

    async syncUnReadMsgCount() {
        if (this.userSession == null) {
            return;
        }
        const res = await callApi(appStore.userMsgApiClient.getStatus({
            sessionId: this.userSession,
        }).response);
        this._unReadMsgCount = res.unreadCount;
    }
}

export const userStore = $state(new UserStore());